<?php

namespace Medicina\BackendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Medicina\KernelBundle\Entity\User;
use Medicina\BackendBundle\Form\UserType;
use Medicina\BackendBundle\Form\UserPerfilType;
use Medicina\BackendBundle\Form\UserChangePasswordType;
use Symfony\Component\Security\Core\SecurityContext;

//use Medicina\BackendBundle\Form\UserSearchType;

class UserController extends Controller {

    const SESSION_EMAIL = 'user_send_resetting_email/email';

    public function loginAction() {
        $request = $this->getRequest();
        $session = $request->getSession();

        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
        }

        return $this->render('BackendBundle:User:login.html.twig', array(
                    // last username entered by the user
                    'last_username' => $session->get(SecurityContext::LAST_USERNAME),
                    'error' => $error,
                ));
    }

    /**
     * Lists all Tipodecargo entities.
     *
     */
    public function indexAction() {
        $entity = new User();
        $em = $this->getDoctrine()->getEntityManager();
        $paginador = $this->get('ideup.simple_paginator');
        $paginador->setItemsPerPage(10);
        $request = $this->getRequest();
        $usuarios = $em->getRepository('MedicinaKernelBundle:User')->findAll();
        $entities = $paginador->paginate($usuarios)->getResult();

        return $this->render('BackendBundle:User:index.html.twig', array(
                    'entities' => $entities,
                    'paginador' => $paginador,
                    'delete_form' => $this->createDeleteForm()->createView()
                ));
    }

    /**
     * Finds and displays a User entity.
     *
     */
    public function showAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('MedicinaKernelBundle:User')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        $roles = $entity->getUserRoles();

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('BackendBundle:User:show.html.twig', array(
                    'entity' => $entity,
                    'roles' => $roles,
                    'delete_form' => $deleteForm->createView(),
                ));
    }

    /**
     * Displays a form to create a new User entity.
     *
     */
    public function newAction() {
        $entity = new User();
        $form = $this->createForm(new UserType(), $entity);

        return $this->render('BackendBundle:User:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView()
                ));
    }

    /**
     * Creates a new User entity.
     *
     */
    public function createAction() {
        $entity = new User();
        $request = $this->getRequest();
        $form = $this->createForm(new UserType(), $entity);
        $form->bindRequest($request);

        if ($form->isValid()) {
            $this->setSecurePassword($entity);
            $entity->setResetPassword(TRUE);
            $em = $this->getDoctrine()->getEntityManager();
            $default_role = $em->getRepository('MedicinaKernelBundle:User')->getROLE_USER();

            try {
                $entity->setDefaultUserRole($default_role);
                $em->persist($entity);
                $em->flush();
                $this->get('session')->setFlash('notice', 'Usuario dado de alta con éxito');

                return $this->redirect($this->generateUrl('user'));
            } catch (\PDOException $e) {

//                throw new \Exception($e->getMessage());
                if (strpos($e->getMessage(), 'UNIQ_AD8A54A9F85E0677') !== false) {
                    $this->get('session')->setFlash('error', 'Ya existe un usuario con el nombre de usuario ingresado');
                }
                if (strpos($e->getMessage(), 'UNIQ_AD8A54A97F8F253B') !== false) {
                    $this->get('session')->setFlash('error', 'Ya existe un usuario con el nro de DNI ingresado');
                }

                return $this->render('BackendBundle:User:new.html.twig', array(
                            'entity' => $entity,
                            'form' => $form->createView()
                        ));
            }
        }
    }

    /**
     * Displays a form to edit an existing Cargo entity.
     *
     */
    public function editAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('MedicinaKernelBundle:User')->find($id);

        $editForm = $this->createForm(new UserType(), $entity, array('isNew' => false));
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('BackendBundle:User:edit.html.twig', array(
                    'entity' => $entity,
                    'form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                ));
    }

    //funcion updateAction:
    public function updateAction($id) {
        $em = $this->getDoctrine()->getEntityManager();
        $default_role = $em->getRepository('MedicinaKernelBundle:User')->getROLE_USER();
        $entity = $em->getRepository('MedicinaKernelBundle:User')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find User entity.');
            $this->get('session')->setFlash('error', 'No existe el usuario ingresado');
        }

        $editForm = $this->createForm(new UserType(), $entity, array('isNew' => false));
        $deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();

        //obtiene la contraseña actual -----------------------
//        $current_pass = $entity->getPassword();

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            //evalua si la contraseña fue modificada: ------------------------
//            if ($current_pass != $entity->getPassword()) {
//                $this->setSecurePassword($entity);
//            }

            try {
                $entity->setDefaultUserRole($default_role);
                $em->persist($entity);
                $em->flush();
                $this->get('session')->setFlash('notice', 'Usuario dado de alta con éxito');

                return $this->redirect($this->generateUrl('user'));
            } catch (\PDOException $e) {

//                throw new \Exception($e->getMessage());
                if (strpos($e->getMessage(), 'UNIQ_AD8A54A9F85E0677') !== false) {
                    $this->get('session')->setFlash('error', 'ERROR, Ya existe un usuario con el nombre de usuario ingresado');
                }
                if (strpos($e->getMessage(), 'UNIQ_AD8A54A97F8F253B') !== false) {
                    $this->get('session')->setFlash('error', 'ERROR, Ya existe un usuario con el nro de DNI ingresado');
                }

                return $this->render('BackendBundle:User:edit.html.twig', array(
                            'entity' => $entity,
                            'form' => $editForm->createView()
                        ));
            }


            $this->get('session')->setFlash('notice', 'Usuario actualizado con éxito');
            return $this->redirect($this->generateUrl('user'));
        }

        return array(
            'entity' => $entity,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    private function createDeleteForm() {
        return $this->createFormBuilder()->getForm();
    }

    private function setSecurePassword(&$entity) {
        $entity->setSalt(md5(time()));
        $encoder = new \Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder('sha512', true, 10);
        $password = $encoder->encodePassword($entity->getPassword(), $entity->getSalt());
        $entity->setPassword($password);
    }

    public function perfilAction() {
        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($user) || !$user instanceof \Symfony\Component\Security\Core\User\UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this->render('BackendBundle:User:show_perfil.html.twig', array(
                    'user' => $user,
                ));
    }

    public function editPerfilAction() {
        $user = $this->container->get('security.context')->getToken()->getUser();

        $editForm = $this->createForm(new UserPerfilType(), $user);

        return $this->render('BackendBundle:User:edit_perfil.html.twig', array(
                    'entity' => $user,
                    'form' => $editForm->createView(),
                ));
    }

    public function updatePerfilAction() {
        $user = $this->container->get('security.context')->getToken()->getUser();
        $id = $user->getId();

        $em = $this->getDoctrine()->getEntityManager();
        $default_role = $em->getRepository('MedicinaKernelBundle:User')->getROLE_USER();

        $entity = $em->getRepository('MedicinaKernelBundle:User')->find($id);

        if (!$entity) {
            $this->get('session')->setFlash('error', 'No existe el perfil');
            return $this->redirect($this->generateUrl('persona'));
        }
        $editForm = $this->createForm(new UserPerfilType(), $entity);
        $request = $this->getRequest();
        $editForm->bindRequest($request);
        if ($editForm->isValid()) {
            try {
                $entity->setDefaultUserRole($default_role);
                $em->persist($entity);
                $em->flush();

                return $this->redirect($this->generateUrl('user_perfil'));
            } catch (\PDOException $e) {
                $this->get('session')->setFlash('error', 'Ya existe una persona con el DNI ingresado');

                return $this->render('BackendBundle:Persona:edit.html.twig', array(
                            'entity' => $entity,
                            'form' => $editForm->createView(),
                        ));
            }
        }

        return array(
            'entity' => $entity,
            'form' => $editForm->createView(),
        );
    }

    /**
     * Change user password
     */
    public function changePasswordAction() {

        $user = $this->container->get('security.context')->getToken()->getUser();

        $editForm = $this->createForm(new UserChangePasswordType(), $user);

        return $this->render('BackendBundle:User:changePassword.html.twig', array(
                    'entity' => $user,
                    'form' => $editForm->createView(),
                ));
    }

    /*
     * Update password
     */

    public function updatePasswordAction() {
        $user = $this->container->get('security.context')->getToken()->getUser();
        $id = $user->getId();

        $em = $this->getDoctrine()->getEntityManager();
        $default_role = $em->getRepository('MedicinaKernelBundle:User')->getROLE_USER();

        $entity = $em->getRepository('MedicinaKernelBundle:User')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        $editForm = $this->createForm(new UserChangePasswordType(), $entity);

        $request = $this->getRequest();

        $editForm->bindRequest($request);

        try {
            $this->setSecurePassword($entity);
            $entity->setResetPassword(TRUE);
            $entity->setDefaultUserRole($default_role);
            $em->persist($entity);
            $em->flush();
            $this->get('session')->setFlash('notice', 'Contraseña actualizada con éxito');

            return $this->redirect($this->generateUrl('user'));
        } catch (\PDOException $e) {
            throw new \Exception($e->getTrace());

            $this->get('session')->setFlash('error', 'Ha ocurrido un error al querer actualizar la Contraseña');
            return $this->render('BackendBundle:User:new.html.twig', array(
                        'entity' => $entity,
                        'form' => $form->createView()
                    ));
        }
    }

    /**
     * Generate the redirection url when the resetting is completed.
     *
     * @param \FOS\UserBundle\Model\UserInterface $user
     *
     * @return string
     */
    protected function getRedirectionUrl(UserInterface $user) {
        return $this->container->get('router')->generate('fos_user_profile_show');
    }

    protected function setFlash($action, $value) {
        $this->container->get('session')->setFlash($action, $value);
    }

    /**
     * Request reset user password: show form
     */
    public function requestAction() {
        return $this->container->get('templating')->renderResponse('BackendBundle:User:request.html.twig');
    }

    /**
     * Request reset user password: submit form and send email
     */
    public function sendEmailAction() {
        $username = $this->container->get('request')->request->get('username');
        $em = $this->getDoctrine()->getEntityManager();
        $user = new User();
        $user = $this->getDoctrine()
                ->getRepository('MedicinaKernelBundle:User')
                ->getUserByUsername($username)
        ;



        if (empty($user)) {
            $this->get('session')->setFlash('error', 'No existe el usuario');
            return $this->redirect($this->generateUrl('login'));
        }
        $user = $user[0];

        $email = $user->getEmail();
        $user->generateConfirmationToken();
        $this->container->get('session')->set(static::SESSION_EMAIL, $email);
        try {
            $this->sendResettingEmailMessage($user);
        } catch (\Exception $e) {
            $this->get('session')->setFlash('error', 'Ha ocurrido un error al querer enviar el mail, revise su conexion');
            return $this->redirect($this->generateUrl('login'));
        }       
        
        $default_role = $em->getRepository('MedicinaKernelBundle:User')->getROLE_USER();
        $user->setDefaultUserRole($default_role);
        $em->persist($user);
        $em->flush();

        $email = '...' . strstr($email, '@');
        return $this->render('BackendBundle:User:checkEmail.html.twig', array(
                    'email' => $email
                ));
    }

    public function sendResettingEmailMessage($user) {
        $host = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://" . $_SERVER['HTTP_HOST'];

        $url = $host . $this->get('router')->generate('user_resetting_reset', array('token' => $user->getConfirmationToken()));   
            $this->sendEmailMessage($user->getUsername(), $user->getEmail(), $url);
      
    }

    protected function sendEmailMessage($username, $toEmail, $urlReset) {
        $body = "Hola " . $username . " ! <br>" .
                "Para restablecer tu contraseña, por favor visita " . $urlReset . "<br><br>" .
                "Atentamente, <br>" .
                "Dpto. de Informática <br>" .
                "Tel: (0221) - 424 1596 Int. 330 <br>" .
                "E-mail: informatica@med.unlp.edu.ar <br>";
        $mailer = $this->container->get('mailer');
        $message = \Swift_Message::newInstance()
                ->setSubject('Bienvenido ' . $username)
                ->setFrom('concursosdocentes2@gmail.com')
                ->setTo($toEmail)
                ->setBody($body, 'text/html');

        $mailer->send($message);
    }

    /**
     * Reset user password
     */
    public function resetAction($token) {
        $em = $this->getDoctrine()->getEntityManager();
        $user = new User();
        $user = $this->getDoctrine()
                ->getRepository('MedicinaKernelBundle:User')
                ->findUserByConfirmationToken($token)
        ;
        $default_role = $em->getRepository('MedicinaKernelBundle:User')->getROLE_USER();


        if (null === $user) {
            $this->get('session')->setFlash('notice', 'No existe el token "$token"');
            return $this->redirect($this->generateUrl('login'));
        }

        $form = $this->createForm(new UserChangePasswordType(), $user);
        $request = $this->getRequest();
        if ($request->getMethod() === 'POST') {

            $request = $this->getRequest();

            $form->bindRequest($request);

            try {
                $this->setSecurePassword($user);
                $user->setResetPassword(TRUE);
                //  $user->setConfirmationToken(NULL);
                $user->setDefaultUserRole($default_role);
                $em->persist($user);
                $em->flush();
                $this->get('session')->setFlash('notice', 'Contraseña actualizada con éxito. Debe Ingresar con su nueva contraseña.');

                return $this->redirect($this->generateUrl('login'));
            } catch (\PDOException $e) {
                throw new \Exception($e->getTrace());

                $this->get('session')->setFlash('error', 'Ha ocurrido un error al querer actualizar la Contraseña');

                return $this->container->get('templating')->renderResponse('BackendBundle:User:reset.html.twig', array(
                            'token' => $token,
                            'form' => $form->createView(),
                        ));
            }
        }

        return $this->container->get('templating')->renderResponse('BackendBundle:User:reset.html.twig', array(
                    'token' => $token,
                    'form' => $form->createView(),
                ));
    }

    public function deleteAction($id) {
        $em = $this->getDoctrine()->getEntityManager();
        $entity = $em->getRepository('MedicinaKernelBundle:User')->find($id);
        if (!$entity) {
            $ $this->get('session')->setFlash('notice', 'No se encontro el Usuario');
        } else {
            if ($id == 1) {
                $this->get('session')->setFlash('notice', 'El usuario ' . $usuario . ', no se puede borrar por cuestiones de seguridad.');
                return $this->redirect($this->generateUrl('user'));
            }
            try {
                $usuario = $entity->getUsername();
                $em->remove($entity);
                $em->flush();
                $this->get('session')->setFlash('notice', 'El usuario' . $usuario . ', se borro con éxito');
            } catch (\PDOException $e) {
                $this->get('session')->setFlash('notice', 'No es posible borrar el usuario ' . $usuario);
            }
        }
        return $this->redirect($this->generateUrl('user'));
    }

}